package model

import (
	"video-management-system/userrpc/userrpc"

	"gorm.io/gorm"
)

type VideoInfo struct {
	gorm.Model
	Uid           int    `gorm:"type:int"`
	VideoTitle    string `gorm:"type:varchar(30);not null"`
	VideoCategory string `gorm:"type:varchar(30);not null"`
	VideoLink     string `gorm:"type:varchar(500);not null;comment:存储云端视频的地址"`
	CoverLink     string `gorm:"type:varchar(500);not null;comment:存储云端封面图片的地址"`
	VideoIntro    string `gorm:"type:varchar(500);not null;comment:对视频内容的描述"`
	PlayNum       string `gorm:"type:varchar(30);not null;default:0;comment:统计视频的播放次数"`
	LikeNum       string `gorm:"type:varchar(30);not null;default:0;comment:统计视频的点赞次数"`
	CollectNum    string `gorm:"type:varchar(30);not null;default:0;comment:统计视频的收藏次数"`
	CommentNum    string `gorm:"type:varchar(30);not null;default:0;comment:统计视频的评论次数"`
	VideoStatus   string `gorm:"type:varchar(30);not null;comment:0-已发布，1-草稿，2-下架，默认值为1"`
	Tid           int    `gorm:"type:int"`
}

func (i *VideoInfo) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(i).Error
}
func (i *VideoInfo) FindVideoById(db *gorm.DB, vid int64) error {
	return db.Debug().Where("id=?", vid).Find(i).Error
}

func (i *VideoInfo) UpdateVideo(db *gorm.DB, vid int64) error {
	return db.Debug().Where("id=?", vid).Updates(i).Error
}

func (i *VideoInfo) VideoShow(db *gorm.DB, vid int64) userrpc.VideoShowResponse {
	var list userrpc.VideoShowResponse
	db.Debug().Model(&VideoInfo{}).Select("users.*,video_infos.*").
		Joins("left join users ON   users.id = video_infos.uid").
		Where("video_infos.id=?", vid).First(&list)
	db.Debug().Model(&VideoInfo{}).Where("video_infos.id=?", vid).Update("play_num", gorm.Expr("play_num  + ?", 1))
	return list
}
func VideoList(db *gorm.DB, in *userrpc.VideoListRequest) []*userrpc.VideoList {
	var list []*userrpc.VideoList
	tx := db.Debug().Model(&VideoInfo{}).Select("users.*,video_infos.*").
		Joins("left join users ON users.id = video_infos.uid")
	if in.SortType == 0 {
		tx.Order("video_infos.play_num desc")
	}
	if in.SortType == 1 {
		tx.Order("video_infos.created_at desc")
	}
	tx.Scopes(Paginate(int(in.Page), int(in.Size))).Find(&list)
	return list
}
func VideoTopicList(db *gorm.DB, tid int64) []*userrpc.VideoTopicList {
	var list []*userrpc.VideoTopicList
	db.Debug().Model(&VideoInfo{}).Select("users.*,video_infos.*").
		Joins("LEFT JOIN users ON users.id = video_infos.uid").
		Where("video_infos.tid=?", tid).Order("play_num desc").
		Limit(3).Find(&list)
	return list
}
